﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using ViCode_LeVi.Data;
using System.IO;

namespace ViCode_LeVi.Engines
{
    public static class EngineAutoSave
    {
        #region private member
        private static bool bProcessEngine = true;
        private static AutoResetEvent are = new AutoResetEvent(false);
        private static Thread thread;
        private static TimeSpan timeOut
        {
            get
            {
                return TimeSpan.FromSeconds(5*30);
            }
        }
        #endregion

        #region Engine
        // 1. Start Engine
        public static bool StartEngine()
        {
            thread = new Thread(new ThreadStart(Process));
            thread.IsBackground = true;
            thread.Start();

            return true;
        }

        // 2.Signal
        public static void SignalEngine()
        {
            are.Set();
        }

        // 3.Stop Sender Engine
        public static bool StopEngine()
        {
            if (thread != null)
            {
                bProcessEngine = false;
                are.Set();
            }
            return true;
        }
        #endregion

        #region Process
        static bool IsWorking = false;
        public static void Process()
        {
            while (bProcessEngine)
            {
                // Block current thread until receive a signal or spent timeOut
                are.WaitOne(timeOut, false);
                if (IsWorking == false)
                {
                    IsWorking = true;
                    try
                    {
                        AutoSaveRun();
                    }
                    catch (Exception ex)
                    {
                    }
                    IsWorking = false;
                }
            }
        }
        #endregion
        private static void AutoSaveRun()
        {
            try
            {
                if (!File.Exists(ProjectData.FileSave))
                {
                    ProjectData.Intance.Save();
                }
            }
            catch (Exception ex)
            {          
            }         
        }
    }
}
